﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tauren.Business.DLL.Base;
using Tauren.Business.DLL.OrganizationDLL;
using Tauren.Business.DLL.Resouces;
using Tauren.Business.Entity.Config;
using Tauren.Business.Entity.Const;
using Tauren.Business.Entity.Enum;
using Tauren.Business.Entity.Global;
using Tauren.Business.Entity.Input;
using Tauren.Business.Entity.Model;
using Tauren.Business.Entity.Output;
using Tauren.Business.Infrastructure.Globals;

namespace Tauren.Business.Service.OrganizationBLL
{
    public class PositionServices : Base.BaseService, IOrganizationServices
    {
        private IOrganizatioBusiness business;
        /// <summary>
        /// 组织结构
        /// </summary>
        /// <param name="baseDLL"></param>
        /// <param name="connectionBLL"></param>
        /// <param name="resourcesBusiness"></param>
        public PositionServices(IOrganizatioBusiness _business, IConnectionBLLBase connectionBLL, IMenuResourcesBusiness resourcesBusiness) : base(_business, connectionBLL, resourcesBusiness)
        {
            this.business = _business;
            this.ResourcesInfo = this.GetResources(GlobalConst.RESOURCES_FLAG_MODULE_ORGANIZATION_KEY);
            this.JudePrmission(GlobalConst.RESOURCES_FLAG_MODULE_ORGANIZATION_KEY.ToLower());
        }

        public IResponseMessage Tree()
        {

            List<Entity.Model.Unitinfo> Companys = baseDLL.All<Entity.Model.Unitinfo>();
            List<Entity.Model.Organization> Organizations = baseDLL.All<Entity.Model.Organization>();
            List<GlobalTree> globalTrees = new List<GlobalTree>();
            Companys.Where(o => o.ParentId == 0 && !o.HaveDelete).ToList().ForEach(o =>
            {
                globalTrees.Add(new GlobalTree()
                {
                    Icon = "",
                    Id = o.UnitId,
                    Label = Global.Language == (LanguageType.zh_cn.ToString().Replace("_", "-")) ? o.CNName : string.IsNullOrEmpty(o.ENName) ? o.CNName : o.ENName,
                    Code = o.UnitCode,
                    CNName = o.CNName,
                    ENName = o.ENName,
                    ParentId = o.ParentId.Value,
                    Children = GenerateChildUnitTreeInfo(o.UnitId, Companys, Organizations),
                    UseNodeCss = !o.Enable || o.HaveDelete,
                    NodeType = OrgationalType.unit.ToString(),
                    Level = o.Level
                });
            });
            return globalTrees.Succeed();
        }

        private List<GlobalTree> GenerateChildUnitTreeInfo(int ParentId, List<Unitinfo> companys, List<Organization> organizations)
        {
            List<GlobalTree> _OutPuts = new List<GlobalTree>();
            List<Unitinfo> childMenus = companys.Where(o => !o.HaveDelete && o.ParentId == ParentId && !o.HaveDelete).ToList();
            if (childMenus.Any())
            {
                childMenus.ForEach(o =>
                {
                    _OutPuts.Add(new GlobalTree()
                    {
                        Icon = "",
                        Id = o.UnitId,
                        Label = Global.Language == (LanguageType.zh_cn.ToString().Replace("_", "-")) ? o.CNName : string.IsNullOrEmpty(o.ENName) ? o.CNName : o.ENName,
                        Code = o.UnitCode,
                        CNName = o.CNName,
                        ENName = o.ENName,
                        ParentId = o.ParentId.Value,
                        Children = GenerateChildUnitTreeInfo(o.UnitId, companys, organizations),
                        UseNodeCss = !o.Enable || o.HaveDelete,
                        NodeType = OrgationalType.unit.ToString(),
                        Level = o.Level
                    });
                });
            }
            List<Organization> orgs = organizations.Where(o => o.ParentId == 0 && o.UnitId == ParentId && !o.HaveDelete).ToList();
            if (orgs.Any())
            {
                orgs.ForEach(o =>
                {
                    _OutPuts.Add(new GlobalTree()
                    {
                        Icon = "",
                        Id = o.OrgId,
                        Label = Global.Language == (LanguageType.zh_cn.ToString().Replace("_", "-")) ? o.CNName : string.IsNullOrEmpty(o.ENName) ? o.CNName : o.ENName,
                        Code = o.OrgCode,
                        CNName = o.CNName,
                        ENName = o.ENName,
                        ParentId = o.ParentId.Value,
                        Children = GenerateChildOrgTreeInfo(o.OrgId, organizations),
                        NodeType = OrgationalType.organization.ToString(),
                        Parameters = new List<Options>() { new Entity.Output.Options() { Label = "companyId", Value = o.UnitId } },
                        Level = o.Level
                    });
                });
            }
            return _OutPuts;
        }

        private List<GlobalTree> GenerateChildOrgTreeInfo(int ParentId, List<Organization> organizations)
        {
            List<GlobalTree> _OutPuts = new List<GlobalTree>();
            List<Organization> orgs = organizations.Where(o => o.ParentId == ParentId && !o.HaveDelete).ToList();
            if (orgs.Any())
            {
                orgs.ForEach(o =>
                {
                    _OutPuts.Add(new GlobalTree()
                    {
                        Icon = "",
                        Id = o.OrgId,
                        Label = Global.Language == (LanguageType.zh_cn.ToString().Replace("_", "-")) ? o.CNName : string.IsNullOrEmpty(o.ENName) ? o.CNName : o.ENName,
                        Code = o.OrgCode,
                        CNName = o.CNName,
                        ENName = o.ENName,
                        ParentId = o.ParentId.Value,
                        Children = GenerateChildOrgTreeInfo(o.OrgId, organizations),
                        UseNodeCss = !o.Enable || o.HaveDelete,
                        NodeType = OrgationalType.organization.ToString(),
                        Parameters = new List<Options>() { new Entity.Output.Options() { Label = "companyId", Value = o.UnitId.Value } },
                        Level = o.Level
                    });
                });
            }
            return _OutPuts;
        }

        /// <summary>
        /// 获取组织列表数据
        /// </summary>
        /// <param name="queryModel"></param>
        /// <returns></returns>
        public IResponseMessage Pages(QueryModel queryModel)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            TableListModel<PageOrganizationTable> tableListModel = new TableListModel<PageOrganizationTable>();
            List<TableListHeaderModele> Headers = new List<TableListHeaderModele>();
            Headers.Add(new TableListHeaderModele() { Key = "rowNo", Name = this.CommonText("rowno"), Width = 50, Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "orgId", Name = this.Resources("orgid"), Width = 120, Hide = true, Fixed = true });
            Headers.Add(new TableListHeaderModele() { Key = "orgCode", Name = this.Resources("orgcode"), Width = 120, Type = "primary_key", IsTag = true, SorTable = SortType.custom.ToString(), Align = "center", Fixed = true,Filter=true });
            Headers.Add(new TableListHeaderModele() { Key = "cnName", Name = this.CommonText("thcnname"), Type = "primary_name", IsOperation = true, SorTable = SortType.custom.ToString(), Fixed = true, Width = 260, Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "enName", Name = this.CommonText("thenname"), Type = "primary_name", SorTable = SortType.custom.ToString(), Width = 260, Filter = true });
            Headers.Add(new TableListHeaderModele() { Key = "unitName", Name = this.CommonText("thunitname"), Width = 180 });
            Headers.Add(new TableListHeaderModele() { Key = "contact", Name = this.Resources("contact"), Width = 160, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "phone", Name = this.CommonText("thphone"), Width = 160, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Enable", Name = CommonText("thstate"), IsTag = true, Width = 100, Align = "center", SorTable = SortType.custom.ToString() });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creator", Name = CommonText("diccreator"), Width = 120, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "dic_Creatdate", Name = CommonText("diccreatdate"), Width = 160, Align = "center" });
            Headers.Add(new TableListHeaderModele() { Key = "action", Name = "操作", Width = 180, Align = "center" });
            List<PageUnitInfoTable> unitListModels = new List<PageUnitInfoTable>();
            long Total = 0;
            List<PageOrganizationTable> pageOrganizationTables = business.Pages(queryModel, out Total);
            if (pageOrganizationTables.Any())
            {
                pageOrganizationTables.ForEach(o =>
                {
                    o.Dic_Enable = CommonText(o.Enable ? GlobalConst.RESOURCES_CONTENT_ENABLE_KEY : GlobalConst.RESOURCES_CONTENT_DISABLE_KEY);
                    o.Dic_Creator = EmpDictionary.ContainsKey(o.Creator) ? EmpDictionary[o.Creator] : "";
                    o.Dic_Creatdate = o.Creatdate.Value.ToString(GlobalConst.DATE_FORMAT_SECONDS);
                    o.Row_Style = o.Enable ? "" : "danger";
                    o.UnitName = UnitDictionary.ContainsKey(o.UnitId.Value) ? UnitDictionary[o.UnitId.Value] : "";
                    o.Operations = new List<SystemButton>();
                    if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
                    {
                        BuliderButtons(o.Operations, o.OrgCode, o.OrgId, ButtomType.edit);
                        BuliderButtons(o.Operations, o.OrgCode, o.OrgId, ButtomType.detaile);
                        BuliderButtons(o.Operations, o.OrgCode, o.OrgId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        BuliderButtons(o.Operations, o.OrgCode, o.OrgId, ButtomType.delete);
                    }
                    else
                    {
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.edit.ToString()))
                            BuliderButtons(o.Operations, o.OrgCode, o.OrgId, ButtomType.edit);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.detaile.ToString()))
                            BuliderButtons(o.Operations, o.OrgCode, o.OrgId, ButtomType.detaile);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && (o.Value == ButtomType.enable.ToString() || o.Value == ButtomType.disable.ToString())))
                            BuliderButtons(o.Operations, o.OrgCode, o.OrgId, !o.Enable ? ButtomType.enable : ButtomType.disable);
                        if (Buttons.Any(o => o.Location == ButtomLocation.center.ToString() && o.Value == ButtomType.delete.ToString()))
                            BuliderButtons(o.Operations, o.OrgCode, o.OrgId, ButtomType.delete);
                    }
                });
            }
            tableListModel.Body = pageOrganizationTables;
            tableListModel.Total = Total;
            tableListModel.Header = Headers;
            if (Global.IsAdmin && (Buttons is null || !Buttons.Any()))
            {
                BuliderButtons(tableListModel.Operations, "", 0, ButtomType.add);
            }
            else
            {
                if (Buttons.Any(o => o.Value == ButtomType.add.ToString()))
                    BuliderButtons(tableListModel.Operations, "", 0, ButtomType.add);
            }
            return tableListModel.Succeed();
        }

        public IResponseMessage Add(Organization_InPut data)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            var codes = business.IsPermissionCodeRepeat(0, data.OrgCode);
            if (codes) return GlobalErrorType.GLOBAL_REPEAT_CODE.Failure(this.CommonText(GlobalErrorType.GLOBAL_REPEAT_CODE));
            Organization organization;
            ToModel(data, out organization);
            organization.Enable = true;
            organization.Sequence = business.GetSeq();
            organization.Creator = Global.EmpId;
            organization.Modifier = Global.EmpId;
            organization.Creatdate = DateTime.Now;
            organization.Modifdate = DateTime.Now;
            if (business.Add<Organization>(organization) > 0)
                return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
            else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
        }

        public IResponseMessage Edit(Organization_InPut data)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            if (data is null) return GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_INPUT_DATA));
            var codes = business.IsPermissionCodeRepeat(data.OrgId, data.OrgCode);
            if (codes) return GlobalErrorType.GLOBAL_REPEAT_CODE.Failure(this.CommonText(GlobalErrorType.GLOBAL_REPEAT_CODE));
            Organization organization;
            ToModel(data, out organization);
            Organization dbModble = business.Get<Organization>(organization.OrgId);
            if (dbModble is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            organization.Creator = dbModble.Creator;
            organization.Modifier = Global.EmpId;
            organization.Creatdate = dbModble.Creatdate;
            organization.Modifdate = DateTime.Now;
            if (business.Update<Organization>(organization))
                return "".OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_SUCCESSINFO.ToString()));
            else return GlobalErrorType.GLOBAL_SAVE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_SAVE_FAILURE));
        }

        public IResponseMessage Delete(int AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            Organization dbModble = business.Get<Organization>(AutoID);
            if (dbModble is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            dbModble.Enable = false;
            dbModble.Modifier = Global.EmpId;
            dbModble.HaveDelete = true;
            dbModble.Modifdate = DateTime.Now;
            if (business.Update<Organization>(dbModble))
                return "".OnSucceed(this.Resources(GlobalErrorType.GLOBAL_DELETE_SUCCESSINFO));
            else return GlobalErrorType.GLOBAL_DELETE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DELETE_FAILURE));
        }

        public IResponseMessage Get(int AutoID)
        {
            Organization organization = business.Get<Organization>(AutoID);
            Organization_OutPut _OutPut = new Organization_OutPut();
            ToViewModel(organization, out _OutPut);
            if (_OutPut is null) return new Organization_OutPut().Succeed();
            return _OutPut.Succeed();
        }


        public IResponseMessage Config(string PageType)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            List<OutPutConfig> Fields = new List<OutPutConfig>();

            OutPutConfig config = new OutPutConfig();
            config = new OutPutConfig();
            config.Label = this.Resources("orgcode");
            config.FieldKey = "orgCode";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ORGANIZATION_KEY.ToLower();
            config.ControlType = ControlType.text;
            config.Show = true;
            config.Editor = PageType != "view" && PageType != "edit";
            config.Required = PageType != "view" && PageType != "edit";
            Dictionary<object, object> rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                #region 添加验证规则

                rule.Add("required", true);
                rule.Add("message", this.Resources("orgcoderequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 20);
                rule.Add("message", this.Resources("orgcodemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///正则
                rule = new Dictionary<object, object>();
                rule.Add("pattern", "^([a-zA-Z0-9_]){1,20}$");
                rule.Add("message", this.Resources("orgcoderegx"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion
            #region 中文名
            config = new OutPutConfig();
            config.Label = this.CommonText("thcnname");
            config.FieldKey = "cnName";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ORGANIZATION_KEY.ToLower();
            config.ControlType = ControlType.textarea;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                rule.Add("required", true);
                rule.Add("message", this.Resources("cnnamerequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 100);
                rule.Add("message", this.Resources("cnnamemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion
            #region 英文名
            config = new OutPutConfig();
            config.Label = this.CommonText("thenname");
            config.FieldKey = "enName";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ORGANIZATION_KEY.ToLower();
            config.ControlType = ControlType.textarea;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            rule = new Dictionary<object, object>();
            if (PageType != "view")
            {
                rule.Add("required", true);
                rule.Add("message", this.Resources("ennamerequired"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
                ///长度
                rule = new Dictionary<object, object>();
                rule.Add("min", 1);
                rule.Add("max", 200);
                rule.Add("message", this.Resources("ennamemax"));
                rule.Add("trigger", "blur");
                config.Rules.Add(rule);
            }
            Fields.Add(config);
            #endregion 
            config = new OutPutConfig();
            config.Label = this.Resources("contact");
            config.FieldKey = "contact";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ORGANIZATION_KEY.ToLower();
            config.ControlType = ControlType.text;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            Fields.Add(config);
            config = new OutPutConfig();
            config.Label = this.CommonText("thphone");
            config.FieldKey = "phone";
            config.MenuCode = GlobalConst.RESOURCES_FLAG_MODULE_ORGANIZATION_KEY.ToLower();
            config.ControlType = ControlType.text;
            config.Show = true;
            config.Editor = PageType != "view";
            config.Required = PageType != "view";
            Fields.Add(config);
            return Fields.Succeed();
        }

        public IResponseMessage Enable(int AutoID)
        {
            if (!HavePermission) return ErrorType.BUSINESS_WITHOUT_PERMISSION.Failure(this.CommonText(ErrorType.BUSINESS_WITHOUT_PERMISSION));
            Organization dbModble = business.Get<Organization>(AutoID);
            if (dbModble is null) return GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA.Failure(this.CommonText(GlobalErrorType.GLOBAL_NOT_FOUND_DB_DATA));
            dbModble.Enable = !dbModble.Enable;
            dbModble.Modifier = Global.EmpId;
            dbModble.Modifdate = DateTime.Now;
            if (business.Update<Organization>(dbModble))
                return "".OnSucceed(this.CommonText(dbModble.Enable ? GlobalErrorType.GLOBAL_ENABLE_SUCCESSINFO : GlobalErrorType.GLOBAL_DISABLE_SUCCESSINFO));
            else return dbModble.Enable ? GlobalErrorType.GLOBAL_ENABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_ENABLE_FAILURE)) : GlobalErrorType.GLOBAL_DISABLE_FAILURE.OnSucceed(this.CommonText(GlobalErrorType.GLOBAL_DISABLE_FAILURE));
        }
    }
}
